

export default {
  namespaced: true,
  state: {
    // 购物车数组
    cartList: uni.getStorageSync('cartList') || []
  },
  getters: {
    // 购物车的商品总数量
    cartCount(state) {
      let count = 0
      state.cartList.forEach(item => {
        count += item.num
      });
      return count
    },
    // 小选影响全选
    isChecked(state) {
      return state.cartList.length && state.cartList.every(item => item.checked)
    },
    //获取选中数组
    checkedCartList(state) {
      return state.cartList.filter(time => time.checked)
    },
    //计算总数量
    totalCount(state, getters) {
      let totalCount = 0
      getters.checkedCartList.forEach(item => totalCount += item.num)
      return totalCount
    },
    //结算总价格
    totalPrice(state, getters) {
      let totalPrice = 0
      getters.checkedCartList.forEach(item => totalPrice += item.num * item.goods_price)
      return totalPrice
    }
  },
  mutations: {
    cartAdd(state, payload) {
      const index = state.cartList.findIndex(item => item.goods_id === payload.value.goods_id)
      if (index == -1) {
        state.cartList.push({ ...payload.value, num: 1, checked: false })
      } else {
        state.cartList[index].num++
      }
      console.log(state.cartList);
      uni.setStorageSync('cartList', state.cartList);
    },
    // 根据商品的id做切换选中
    cartToggleCheck(state, payload) {
      /* 
     1 根据商品的id 找到元素在数组中的位置 下标 index 
     2 数组[下标].checked = ! 数组[下标].checked;
     3 存一份到缓存中
      */
      const index = state.cartList.findIndex(item => item.goods_id === payload.value)
      state.cartList[index].checked = !state.cartList[index].checked;
      uni.setStorageSync('cartList', state.cartList);
    },
    // 根据商品的id做数量增减
    cartQuantitative(state, payload) {
      console.log(state, payload);
      const index = state.cartList.findIndex(item => item.goods_id === payload.value.id)
      state.cartList[index].num += payload.value.unit
      uni.setStorageSync("cartList", state.cartList)
    },
    // 根据商品的id删除商品
    cartItemDelete(state, payload) {
      const index = state.cartList.findIndex(item => item.goods_id === payload.value)
      state.cartList.splice(index, 1)
      uni.setStorageSync("cartList", state.cartList)
    },
    // 全选影响小选
    cartAllToggle(state, payload) {
      const isChecked = !payload.value
      state.cartList.forEach(item => item.checked = isChecked)
      uni.setStorageSync('cartList', state.cartList);
    }
  },
  actions: {

  }
}